package com.io.webflow.service.impl;

import com.io.config.WrapInt;
import com.io.model.RegisterReq;
import com.io.nettyflow.rounter.ContextManager;
import com.io.protocol.CommonConstants;
import com.io.util.NettyUtils;
import com.io.webflow.service.ChannelService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by yangyx on 2016/8/4.
 */
@Service
public class ChannelServiceImpl implements ChannelService {

    static final Logger logger= LoggerFactory.getLogger(ChannelServiceImpl.class);

    @Autowired
    ContextManager contextManager;

    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/4 11:34
     *登录时验证数据是否重复存储与终端是否与其他部位也有登录
     * 并存储登录信息
     */
    public void delRepeatMsg(ChannelHandlerContext ctx, WrapInt<RegisterReq> obj){
        RegisterReq registerReq=obj.getRefVal();
        registerReq.setCtx(ctx);
        RegisterReq existObj=contextManager.getPrincipalByTid(registerReq.getTerminalID());
        if(null!=existObj&&!NettyUtils.isChannelEqual(registerReq.getCtx(),existObj.getCtx())){
            logger.info("--------删除这个id="+existObj.ctx.channel().id().asLongText());
            existObj.ctx.close();
        }else{
            //把先有通道放进map内
            contextManager.setRegisterReq(registerReq);
            RegisterReq channelObj= (RegisterReq) ctx.channel().attr(CommonConstants.ATTRIBUTE_KEY).get();
            //登录成功后要把登录信息放进去
            if(null==channelObj){
                ctx.channel().attr(CommonConstants.ATTRIBUTE_KEY).set(registerReq);
            }
        }
    }
}
